package com.study6.mybatis.more.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xuly
 * @title: DruidConfig
 * @projectName spring-boot
 * @description: TODO
 * @date 2019-07-2415:55
 **/
@Configuration
@MapperScan(basePackages = {"com.study6.mybatis.more.mapper.erp"},
        sqlSessionFactoryRef = "erpSqlSessionFactory")
public class ErpDruidConfig {

    @Value("${spring.datasource.erp.mapper-locations}")
    private String erplocations;
    @Value("${spring.datasource.erp.type-aliases-package}")
    private String typePackage;


    @ConfigurationProperties(prefix = "spring.datasource.erp")
    @Bean
    public DataSource erpDruidDataSource() {
        return new DruidDataSource();
    }

    @Bean
    public SqlSessionFactory erpSqlSessionFactory(
            @Qualifier("erpDruidDataSource") DataSource dataSource
    ) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        // 配置mapper文件位置
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources(erplocations));
        sqlSessionFactoryBean.setTypeAliasesPackage(typePackage);
        return sqlSessionFactoryBean.getObject();
    }

    @Bean(name = "sentinelSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate erpSqlSessionTemplate(@Qualifier("erpSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }


    /**
     * 配置事物管理器
     *
     * @return
     */
    @Bean(name = "erpTransactionManager")
    @Primary
    public DataSourceTransactionManager erpTransactionManager(
            @Qualifier("erpDruidDataSource") DataSource dataSource
    ) {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }

}
